package mysql

import (
	"manuscript-service/bookrpc/bookrpc"

	"gorm.io/gorm"
)

// 稿件

type Book struct {
	gorm.Model
	Title   string `gorm:"type:varchar(30);not null;comment:稿件标题"`
	Author  string `gorm:"type:varchar(30);not null;comment:稿件作者"`
	Content string `gorm:"type:varchar(30);not null;comment:稿件内容"`
	ClassId int    `gorm:"type:int;not null;comment:类别ID"`
}

// 稿件新增

func (b *Book) BookAdd(db *gorm.DB) error {
	return db.Debug().Create(b).Error
}

// 查询稿件名称是否存在

func (b *Book) FindClass(db *gorm.DB, title string) error {
	return db.Debug().Where("title=?", title).First(b).Error
}

// 稿件列表

func BookList(db *gorm.DB) []*bookrpc.BookList {
	/*
		select
		books.id as BookId,
		books.title as Title,
		books.author as Author,
		books.content as Content,
		classes.`name` as ClassName
		from books
		left join classes on classes.id = books.class_id
	*/
	var list []*bookrpc.BookList
	db.Debug().Table("books").
		Select(
			"books.id as BookId",
			"books.title as Title",
			"books.author as Author",
			"books.content as Content",
			"classes.`name` as ClassName",
		).
		Joins("left join classes on classes.id = books.class_id").
		Find(&list)
	return list
}
